package com.fingard.dsp.bank.directbank.hbc11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.File;
import java.text.MessageFormat;
import java.util.Date;

/**
 * @author FanH on 2019/8/26.
 * @version 1.0
 *
 * 参考文档：批量代收付接口文档
 * 实现接口：9188
 */
public class HBC11BatPayRec extends HBC11Base implements IBatPayRec {

    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return null;
    }


    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        retAts.reqSeqID = p_req9188.reqBatchNO;

        SftpPortClient sftpPortClient = null;

        try {
            StringBuilder sbFileContent = new StringBuilder();

            // 文件明细：
            while (p_req9188.readRecord()) {
                String reqSeqId = p_req9188.reqBatchNO;//流水号
                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_req9188.reqHeader.transType)) {
                    oppAct = p_req9188.readedDetail.recAct;
                    oppName = p_req9188.readedDetail.recName;
                } else {
                    oppAct = p_req9188.readedDetail.payAct;
                    oppName = p_req9188.readedDetail.payName;
                }
                String certNum = p_req9188.readedDetail.certNum;//证件号码
                String polNo = p_req9188.readedDetail.sourceNoteCode;//保单号
                String tmpPaySendDate = Format.Date8Format.format(p_req9188.getPayDateTime());//操作日期
                String totalAmt = p_req9188.totalAmt;//交易金额
                String cerType = getBankConfig().getMapValueByKey("certTypeMapping", p_req9188.readedDetail.certType);

                //明细信息:流水号,客户姓名,证件号码,保单号,操作日期,交易金额,银行卡号,证件类型
                String tmpReqBodyDetail = MessageFormat.format("{0},{1},{2},{3},{4},{5},{6},{7}\n", reqSeqId, oppName, certNum, polNo, tmpPaySendDate, totalAmt, oppAct, cerType);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次请求文件内容:\r\n" + sbFileContent.toString());

            //文件名称:保险公司首字母缩写+8位日期+S（代收）/F(代付)+2位序号
            //如：来盘   ZDAL20190820S01.txt
            String tmpRecSendDate = Format.Date8Format.format(p_req9188.getPayDateTime());//操作日期
            String type = "";
            if ("9188".equals(p_req9188.reqHeader.transType)) {
                type = "S";
            }else if("1988".equals(p_req9188.reqHeader.transType)){
                type = "F";
            }
            String bakUpPath = getDataFileDirectory(new Date());
            int maxBatch = 0;
            File dataFileDir = new File(StringHelper.trimEnd(bakUpPath, File.separator) + File.separator + "batRec");
            if (dataFileDir.exists()) {
                int len = dataFileDir.listFiles().length;
                if (len > 0) {
                    maxBatch = len + 1;
                } else {
                    maxBatch = 1;
                }
            } else {
                maxBatch = 1;
            }
            String tmpUploadFileName = bankFront.corpNo + tmpRecSendDate + type + String.format("%2s", maxBatch).replace(" ", "0") + ".txt";
            String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
            String dtatLocalMarkPath = bakUpPath + File.separator + "batRec" + File.separator + p_req9188.reqBatchNO + ".txt";
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            if (FileHelper.existFile(dtatLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_req9188.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
            FileHelper.writeFile(dtatLocalMarkPath, tmpUploadFileName.toString(), getCharset());

            // 上送银保通服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            sftpPortClient = new SftpPortClient(ftpSet);
            sftpPortClient.connectBySSH();
            String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
            FtpReceiver ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);

            retAts.respCode = "0";
            retAts.reqSeqID = p_req9188.reqBatchNO;
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }

        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
